package com.mxfcode.front.bbs_login.service.impl;

import com.mxfcode.bbs_common.email.MailClient;
import com.mxfcode.bbs_common.table_operation.service.UtilService;
import com.mxfcode.bbs_common.util.aes.AESUtil;
import com.mxfcode.bbs_common.util.community.CommunityConstant;
import com.mxfcode.bbs_common.util.community.CommunityUtil;
import com.mxfcode.entity.TSLoginTicket;
import com.mxfcode.front.bbs_login.mapper.LoginMapper;
import com.mxfcode.front.bbs_login.mapper.LoginTicketMapper;
import com.mxfcode.front.bbs_login.service.LoginService;
import com.mxfcode.entity.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author moxiufeng
 * @date 2021/2/16 16:49
 */
@Service
public class LoginServiceImpl implements LoginService,CommunityConstant {

    @Autowired
    private MailClient mailClient;
    @Autowired
    private TemplateEngine templateEngine;

    @Resource
    private LoginMapper loginMapper;

    @Autowired
    private UtilService utilService;

    @Resource
    private LoginTicketMapper loginTicketMapper;
    @Value("${bbs.path.domain}")
    private String domain;

    @Override
    public Map<String,Object> register(TSUser tsUser) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //验证账号
        TSUser user = loginMapper.selectByName(tsUser.getUserName());
        if(user != null){
            map.put("errorMsg","该账号已注册");
            return  map;
        }

        //注册账户
        tsUser.setId(CommunityUtil.generateUUID());
        tsUser.setPassword(AESUtil.aesEncrypt(tsUser.getPassword(), CommunityConstant.ASE_KEY));
        tsUser.setType(0);
        tsUser.setStatus(0);
        //TODO : 默认给新注册普通会员权限
        tsUser.setUserStatus(1);
        tsUser.setRoleId("0");
        tsUser.setActivationCode(CommunityUtil.generateUUID());
        tsUser.setAvatarUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        tsUser.setCreateDate(new Date());
        loginMapper.insertUser(tsUser);

        //激活邮件
        Context context = new Context();
        context.setVariable("email", tsUser.getUserName());
        // http://localhost:8080/activation/101/code
        String url = domain  + "/activation/" + tsUser.getId() + "/" + tsUser.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(tsUser.getUserName(), "激活账号", content);
        return map;
    }

    @Override
    public int activation(String userId, String code) {
        TSUser user = loginMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            loginMapper.updateStatus(userId, 1);
//            clearCache(userId);
            return ACTIVATION_SUCCESS;
        } else {
            return ACTIVATION_FAILURE;
        }
    }

    @Override
    public Map<String, Object> login(String username, String password, long expiredSeconds) throws Exception {
        HashMap<String,Object> map = new HashMap<>();
        //校验账号是否存在
        TSUser user = loginMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg","该账号不存在！");
            return map;
        }
        if(user.getStatus() == 0){
            map.put("usernameMsg","该账号未激活！");
            return map;
        }
        //HedFhDJbDUAf0r6b+pnLDQ==
        password = AESUtil.aesEncrypt(password,CommunityConstant.ASE_KEY);
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确！");
            return map;
        }
        //生成登录凭证
        TSLoginTicket loginTicket = new TSLoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        loginTicketMapper.insertLoginTicket(loginTicket);
        map.put("ticket",loginTicket.getTicket());

        return map;
    }

    @Override
    public TSLoginTicket findLoginTicket(String ticket) {
        return loginTicketMapper.selectByTicket(ticket);
    }

    @Override
    public TSUser findUserById(String userId) {
        return loginMapper.selectById(userId);
    }
}
